﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using SubSonic;
using ExtAspNet;
using System.Security.Principal;



namespace TCMSystem
{
    public partial class _default : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            //string[] loginImages = new string[] { "login_1.png", "login_2.png", "login_3.png", "login_4.png", "login_6.png" };
            //imageLogin.ImageUrl = "~/res/images/login/" + loginImages[new Random().Next(0, loginImages.Length)];

        }

        #endregion

        #region Events

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string userName = tbxUserName.Text.Trim();
            string password = tbxPassword.Text.Trim();

            TblMstUser user = new Select().From<TblMstUser>()
                .Where(TblMstUser.NameColumn).IsEqualTo(userName)
                .ExecuteSingle<TblMstUser>();

            if (user != null)
            {
                if (PasswordUtil.ComparePasswords(user.Password, password))
                {
                    if (!user.Enabled)
                    {
                        Alert.Show("用户未启用，请联系管理员！");
                    }
                    else
                    {
                        // 登录成功
                        logger.Info(String.Format("登录成功：用户“{0}”", user.Name));

                        LoginSuccess(user);

                        //LoginOnlineUser(user);
                        //FormsAuthentication.RedirectFromLoginPage(userName, true);
                        return;
                    }
                }
                else
                {
                    logger.Warn(String.Format("登录失败：用户“{0}”密码错误", userName));
                    Alert.Show("用户名或密码错误！");
                    return;
                }

            }
            else
            {
                logger.Warn(String.Format("登录失败：用户“{0}”不存在", userName));
                Alert.Show("用户名或密码错误！");
                return;
            }
        }


        private void LoginSuccess(TblMstUser user)
        {
            LoginOnlineUser(user);

            int roleId = -1;
            if (user.RoleId.HasValue)
            {
                roleId = user.RoleId.Value;
            }

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, 
                user.Name, 
                DateTime.Now,
                DateTime.Now.AddMinutes(120), 
                true,
                roleId.ToString(), 
                FormsAuthentication.FormsCookiePath);
            string hashTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            userCookie.HttpOnly = true;
            userCookie.Expires = DateTime.Now.AddMinutes(120);
            Response.Cookies.Add(userCookie);
            Response.Redirect(FormsAuthentication.DefaultUrl);
        }


        #endregion
    }
}
